package com.code.jvm.reference.phantom;

import com.code.jvm.reference.Student;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class PhantomClient {
    public static void main(String[] args) {
        ReferenceQueue queue = new ReferenceQueue();
        PhantomReference<Student> reference = new PhantomReference<>(new Student(), queue);

        List<byte[]> bytes = new ArrayList<>();
        //一个线程不断的往字节数组中放数据，触发GC
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                bytes.add(new byte[1024 * 1024]);
            }
        }).start();

        //一个线程从引用队列中获取被回收的虚引用
        new Thread(() -> {
            while (true) {
                Reference poll = queue.poll();
                if (poll != null) {
                    System.out.println("虚引用被回收了：" + poll);
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        scanner.hasNext();
    }
}
